package com.tjec.project.system.service.impl;

import com.tjec.common.constant.AttachmentConstants;
import com.tjec.common.enums.CodeNum;
import com.tjec.common.enums.NumCode;
import com.tjec.common.utils.DateUtils;
import com.tjec.common.utils.SFtpUtil;
import com.tjec.common.utils.ServletUtils;
import com.tjec.common.utils.file.FileNetUrl;
import com.tjec.common.utils.poi.ExcelUtil;
import com.tjec.common.utils.poi.ExcelVo;
import com.tjec.common.utils.poi.ImportExcelUtil;
import com.tjec.framework.security.service.TokenService;
import com.tjec.framework.web.domain.AjaxResult;
import com.tjec.project.businessWorkbench.domain.BmsBusinessDocArchive;
import com.tjec.project.system.domain.*;
import com.tjec.project.system.domain.vo.BmsAttachmentVo;
import com.tjec.project.system.mapper.BmsArchiveTemplateListMapper;
import com.tjec.project.system.mapper.BmsAttachmentMapper;
import com.tjec.project.system.mapper.BmsCategoryAssociatedMapper;
import com.tjec.project.system.mapper.BmsMdArchiveTemplateMapper;
import com.tjec.project.system.mapper.BmsMdBusinessCategoryMapper;
import com.tjec.project.system.service.IBmsAttachmentService;
import com.tjec.project.system.service.IBmsMdArchiveTemplateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 归档模板Service业务层处理
 *
 * @author tjec
 * @date 2020-04-16
 */
@Service
public class BmsMdArchiveTemplateServiceImpl implements IBmsMdArchiveTemplateService {
    @Autowired
    private BmsMdArchiveTemplateMapper bmsMdArchiveTemplateMapper;
    @Autowired
    private IBmsAttachmentService iBmsAttachmentService;
    @Autowired
    private BmsAttachmentMapper bmsAttachmentMapper;
    @Autowired
    private BmsCategoryAssociatedMapper bmsCategoryAssociatedMapper;
    @Autowired
    private BmsMdBusinessCategoryMapper bmsMdBusinessCategoryMapper;
    @Autowired
    private SFtpUtil sftp;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private BmsArchiveTemplateListMapper bmsArchiveTemplateListMapper;

    /**
     * 查询归档模板
     *
     * @param guid 归档模板ID
     * @return 归档模板
     */
    @Override
    public BmsMdArchiveTemplate selectBmsMdArchiveTemplateById(String guid) {
        BmsMdArchiveTemplate entity = bmsMdArchiveTemplateMapper.selectBmsMdArchiveTemplateById(guid);

        if (StringUtils.isNotBlank(entity.getAttachmentId())) {
            entity.setAttachmentList(iBmsAttachmentService.selectBmsAttachmentDownload(entity.getAttachmentId()));
        }

        //业务类型
        List<BmsMdBusinessCategory> bmsMdBusinessCategoryList = bmsMdBusinessCategoryMapper.selectBusinessCategoryByCategoryAssociated(guid, null);
        entity.setBusinessCategoryList(bmsMdBusinessCategoryList);
        //转化guid成List<String>
        List<String> lists= new ArrayList<String>();
        for (BmsMdBusinessCategory bmsMdBusinessCategory:bmsMdBusinessCategoryList) {
            lists.add(bmsMdBusinessCategory.getGuid()) ;
        }
        entity.setBusinessCategoryIds(lists);
        return entity;
    }

    /**
     * 查询归档模板列表
     *
     * @param bmsMdArchiveTemplate 归档模板
     * @return 归档模板
     */
    @Override
    public List<BmsMdArchiveTemplate> selectBmsMdArchiveTemplateList(BmsMdArchiveTemplate bmsMdArchiveTemplate) {
        List<BmsMdArchiveTemplate> list = bmsMdArchiveTemplateMapper.selectBmsMdArchiveTemplateList(bmsMdArchiveTemplate);
        list.forEach(item -> {
            if (StringUtils.isNotBlank(item.getAttachmentId())) {
                item.setAttachmentList(iBmsAttachmentService.selectBmsAttachmentDownload(item.getAttachmentId()));
            }
            item.setBusinessCategoryList(bmsMdBusinessCategoryMapper.selectBusinessCategoryByCategoryAssociated(item.getGuid(),bmsMdArchiveTemplate.getBusinessCategoryId()));
        });
        return list;
    }

    /**
     * 新增归档模板
     * 
     * @param bmsMdArchiveTemplate 归档模板
     * @return 结果
     */
    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int insertBmsMdArchiveTemplate(BmsMdArchiveTemplate bmsMdArchiveTemplate)
    {
        bmsMdArchiveTemplate.setCreateTime(DateUtils.getNowDate());
        int ret = bmsMdArchiveTemplateMapper.insertBmsMdArchiveTemplate(bmsMdArchiveTemplate);
        if (ret > -1) {
            updateAttachment(bmsMdArchiveTemplate);
            updateBusinessCategory(bmsMdArchiveTemplate);
            bmsMdArchiveTemplate.setBusinessCategoryId(StringUtils.join(bmsMdArchiveTemplate.getBusinessCategoryIds(),","));
            insertBatchArchiveList(bmsMdArchiveTemplate,"1");
        }
        return ret;
    }

    public void insertBatchArchiveList(BmsMdArchiveTemplate bmsMdArchiveTemplate,String flag) {//1:新增，2:修改
    	if(com.tjec.common.utils.StringUtils.isNotBlank(bmsMdArchiveTemplate.getAttachmentId())) {
    		//如果是修改，需要判断附件是否变化
    		if("2".equals(flag)) {
    			//获取原来的数据
    			bmsArchiveTemplateListMapper.deleteBmsArchiveTemplateListByTemplateId(bmsMdArchiveTemplate.getGuid());
    		}
    		
    		List<BmsAttachmentVo> attachments = iBmsAttachmentService.selectBmsAttachmentDownload(bmsMdArchiveTemplate.getAttachmentId());
    		if (CollectionUtils.isEmpty(attachments)) {
				return;
			}

			StringBuffer sb = new StringBuffer(attachments.get(0).getStoragePath());
			
			File file = null;
			if (attachments.get(0).getStoragePath().startsWith("https://")) {
				file = FileNetUrl.getNetUrlHttps(sb.toString());
			} else {
				file = FileNetUrl.getNetUrlHttp(sb.toString());
			}
			FileInputStream inputStream;
			try {
				inputStream = new FileInputStream(file);
				List<List<Object>> list = ImportExcelUtil.getBankListByExcel(inputStream, "前期咨询-任务管理清单模板文件.xlsx");

				List<BmsArchiveTemplateList> bmsArchiveTemplateLists = new ArrayList<BmsArchiveTemplateList>();
				
				String[] businessTypeIds = StringUtils.split(bmsMdArchiveTemplate.getBusinessCategoryId(),",");
				for (String string : businessTypeIds) {
					for (int i = 0; i < list.size(); i++) {
						BmsArchiveTemplateList bmsArchiveTemplateList = new BmsArchiveTemplateList();
						bmsArchiveTemplateList.setCreateBy(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
						bmsArchiveTemplateList.setBusinessTypeId(string);
						bmsArchiveTemplateList.setTemplateId(bmsMdArchiveTemplate.getGuid());
						for (int j = 0; j < list.get(i).size(); j++) {
							if (j == 0) {
								bmsArchiveTemplateList.setArchiveFileName(list.get(i).get(j).toString());
								bmsArchiveTemplateList.setCreateBy(
										tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
							} else if (j == 1) {
								bmsArchiveTemplateList.setIsMust(list.get(i).get(j).toString());
							} else if (j == 2) {
								bmsArchiveTemplateList.setShape(list.get(i).get(j)==null?"":list.get(i).get(j).toString());
							}
						}
						
						if(!"".equals(bmsArchiveTemplateList.getArchiveFileName()) && bmsArchiveTemplateList.getArchiveFileName()!=null) {
							bmsArchiveTemplateLists.add(bmsArchiveTemplateList);
						}
					}
				}
				
				bmsArchiveTemplateListMapper.insertBmsArchiveTemplateLists(bmsArchiveTemplateLists);
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
    	
    }
    
    
    /**
     * 更新业务类别表
     * @param entity
     */
    private void updateBusinessCategory(BmsMdArchiveTemplate entity) {
        if(!CollectionUtils.isEmpty(entity.getBusinessCategoryIds())){
            List<String> categoryList = entity.getBusinessCategoryIds();
            //添加关联库的数据  业务类别的关联
            for (String bms:categoryList) {
                BmsCategoryAssociated associated = new BmsCategoryAssociated();
                associated.setCategoryGuid(bms);
                associated.setParentGuid(entity.getGuid());
                associated.setGuid(UUID.randomUUID().toString());
                associated.setFlag(CodeNum.SIX.getCode());
                bmsCategoryAssociatedMapper.insertBmsCategoryAssociated(associated);
            }
        }
    }

    /**
     * 新增、修改时更新文件表
     *
     * @param entity
     */
    private void updateAttachment(BmsMdArchiveTemplate entity) {
        if (StringUtils.isNotBlank(entity.getAttachmentId())) {
            BmsAttachment bmsAttachment = new BmsAttachment();
            bmsAttachment.setGuid(entity.getAttachmentId());
            bmsAttachment.setBizId(entity.getGuid());
            bmsAttachment.setDelFlag(NumCode.ZERO.getCode());
            bmsAttachment.setCategory(AttachmentConstants.BUSINESS_DOC);
            iBmsAttachmentService.updateBmsAttachment(bmsAttachment);
        }
    }

    /**
     * 修改归档模板
     * 
     * @param bmsMdArchiveTemplate 归档模板
     * @return 结果
     */
    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int updateBmsMdArchiveTemplate(BmsMdArchiveTemplate bmsMdArchiveTemplate)
    {
        bmsMdArchiveTemplate.setUpdateTime(DateUtils.getNowDate());
        int ret = bmsMdArchiveTemplateMapper.updateBmsMdArchiveTemplate(bmsMdArchiveTemplate);
        if (ret > -1) {
            bmsAttachmentMapper.updateBmsAttachmentByBizId(new String[]{bmsMdArchiveTemplate.getGuid()}, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
            updateAttachment(bmsMdArchiveTemplate);

            //对业务类别进行修改先删除在重现添加
            bmsCategoryAssociatedMapper.deleteBmsCategoryAssociatedByParentId(bmsMdArchiveTemplate.getGuid());
            updateBusinessCategory(bmsMdArchiveTemplate);
            
            bmsMdArchiveTemplate.setBusinessCategoryId(StringUtils.join(bmsMdArchiveTemplate.getBusinessCategoryIds(),","));
            insertBatchArchiveList(bmsMdArchiveTemplate,"2");
        }
        return ret;
    }

    /**
     * 批量删除归档模板
     * 
     * @param guids 需要删除的归档模板ID
     * @return 结果
     */
    @Override
    public int deleteBmsMdArchiveTemplateByIds(String[] guids)
    {
    	bmsArchiveTemplateListMapper.deleteBmsArchiveTemplateListByTemplateIds(guids);
        return bmsMdArchiveTemplateMapper.deleteBmsMdArchiveTemplateByIds(guids);
    }

    /**
     * 删除归档模板信息
     * 
     * @param guid 归档模板ID
     * @return 结果
     */
    @Override
    public int deleteBmsMdArchiveTemplateById(String guid)
    {
        return bmsMdArchiveTemplateMapper.deleteBmsMdArchiveTemplateById(guid);
    }
    @SuppressWarnings("unchecked")
	@Override
    public AjaxResult validation(String fileUrl) throws Exception {
    	System.out.println("fileUrl========"+fileUrl);
        Boolean ret = false;
        String path = fileUrl.substring(0, fileUrl.lastIndexOf("/") + 1);
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
        sftp.connectServer();
        InputStream in = sftp.download(path, fileName);
        //InputStream in = new FileInputStream(fileUrl);
        ExcelUtil<ExcelVo> util = new ExcelUtil<ExcelVo>(ExcelVo.class);
        List<ExcelVo> list = new ArrayList<ExcelVo>();
        
        list = util.toList(in, fileName, 0, 2);
        if(list==null || list.size()==0) {
        	list = util.toList(in, fileName, 0, 3);
        }
        System.out.println("list========"+list);
        //数据校验
        if (!CollectionUtils.isEmpty(list)) {

            //二级列表
            List<ExcelVo> fourthTaskList = list.stream().filter(a -> StringUtils.isBlank(a.getString2())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(fourthTaskList)) {
                return AjaxResult.error("是否必须为必填项，不能为空");
            }
            //一级列表
            if(list.stream().anyMatch(a -> StringUtils.isBlank(a.getString1()))){
                return AjaxResult.error("归档文件为必填项，不能为空");
            }
            return AjaxResult.success();
        }
        return AjaxResult.error("模板数据格式不正确，请按要求填写");
    }
}
